package com.system.connect.springboot_flowers.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.system.connect.springboot_flowers.entity.Coupons;
import com.system.connect.springboot_flowers.service.ICouponsService;
import com.system.connect.springboot_flowers.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 优惠券表 前端控制器
 * </p>
 *
 * @author yang
 * @since 2025-01-21
 */
@Slf4j
@RestController
@RequestMapping("/api/coupons")
public class CouponsController {

    @Autowired
    private ICouponsService couponsService;

    /**
     * 添加优惠券
     * @param coupons
     * @return
     */
    @PostMapping
    public R addCoupons(@RequestBody Coupons coupons) {
        couponsService.save(coupons);
        return R.success("添加成功");
    }

    @GetMapping
    public R getCoupons() {
        return R.success(couponsService.list());
    }

    /**
     * 获取所有可用优惠券列表
     */
    @GetMapping("/list")
    public R<List<Coupons>> getAvailableCoupons() {
        try {
            QueryWrapper<Coupons> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", "ACTIVE")  // 只查询激活状态的优惠券
                       .orderByDesc("created_at");
            
            List<Coupons> coupons = couponsService.list(queryWrapper);
            return R.success(coupons);
        } catch (Exception e) {
            log.error("获取优惠券列表失败", e);
            return R.error("获取优惠券列表失败，请重试");
        }
    }

    /**
     * 根据ID获取优惠券详情
     */
    @GetMapping("/{id}")
    public R<Coupons> getCouponById(@PathVariable Integer id) {
        try {
            Coupons coupon = couponsService.getById(id);
            if (coupon == null) {
                return R.error("优惠券不存在");
            }
            return R.success(coupon);
        } catch (Exception e) {
            log.error("获取优惠券详情失败", e);
            return R.error("获取优惠券详情失败，请重试");
        }
    }

    /**
     * 根据类型获取优惠券列表
     */
    @GetMapping("/type/{type}")
    public R<List<Coupons>> getCouponsByType(@PathVariable String type) {
        try {
            QueryWrapper<Coupons> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type", type)
                       .eq("status", "ACTIVE")
                       .orderByDesc("created_at");
            
            List<Coupons> coupons = couponsService.list(queryWrapper);
            return R.success(coupons);
        } catch (Exception e) {
            log.error("获取优惠券列表失败", e);
            return R.error("获取优惠券列表失败，请重试");
        }
    }
}

